<?php
namespace app\home\controller;
use think\Controller;
use think\Db;
use think\Input;
use app\home\model\Article;

class Details extends Common
{
    const CODE_SUCC = 0;
    const CODE_FAIL = 0;

    /**
     * API获取文章详情
     * 
     * @method GET 
     * @params int  $id  文章id
     */
    public function detail()
    {
        $ret = ['code'=>self::CODE_FAIL, 'data'=> (object)[], 'msg'=>'fail'];
        try {
            $id = intval(input('id'));
            if ($id < 1) {
                throw new \Exception('param error');
            }
            $article = new Article();
            $article_re = $article->field(['id,title,description'])->find($id);
            $ret['code'] = self::CODE_SUCC; 
            $ret['msg'] = 'success';
            $ret['data'] = ($article_re) ? $article_re->getData() : (object)[];
            return json($ret);
        } catch (\Exception $e) {
            $ret['msg'] = $e->getMessage();
            return json($ret);
        }
    }

    /**
     * API获取所有文章列表
     * 
     * @method GET
     */
    public function list()
    {
        $ret = ['code'=>self::CODE_FAIL, 'data'=> (object)[], 'msg'=>'fail'];
        try {
            $id = intval(input('id'));
            if ($id < 1) {
                throw new \Exception('param error');
            }
            $article = new Article();
            $article_re = $article->find($id);
            $ret['code'] = self::CODE_SUCC; 
            $ret['msg'] = 'success';
            $ret['data'] = ($article_re) ? $article_re->getData() : (object)[];
            return json_encode($ret);
        } catch (\Exception $e) {
            $ret['msg'] = $e->getMessage();
            return json($ret);
        }
    }

    public function index()
    {
        $id = intval(input('id'));
        if ($id < 1) {
            return $this->redirect('index/index');
        }
        $article = Db::name('article')->where('id', $id)->find();
        if (!$article) {
            return $this->redirect('index/index');
        }
        $this->assign([
            'article' => $article
        ]);
        return $this->fetch();
    }
}